#!/usr/bin/env python3
"""
Demo script for the Structural Text Analyzer.
Demonstrates various usage patterns and capabilities.
"""

import os
import sys
from pathlib import Path

# Add the parent directory to Python path for imports
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)

from structural_analyzer.analyzer import StructuralTextAnalyzer
from structural_analyzer.config import ConfigManager

def demo_computational_log_analysis():
    """Demo analysis of computational log file."""
    
    print("="*70)
    print("DEMO: Computational Log Analysis")
    print("="*70)
    
    # Use the test data file
    test_file = "../../user_input_files/test_data.txt"
    
    if not os.path.exists(test_file):
        print(f"Test file not found: {test_file}")
        return
        
    # Create analyzer optimized for computational logs
    analyzer = StructuralTextAnalyzer.from_text_type('computational_log', 'demo_output')
    
    # Run complete analysis
    try:
        outputs = analyzer.run_complete_analysis(test_file, "computational_log_demo")
        
        print("\nDEMO COMPLETED SUCCESSFULLY!")
        print(f"Check the 'demo_output' directory for results.")
        
        return outputs
        
    except Exception as e:
        print(f"Demo failed: {e}")
        import traceback
        traceback.print_exc()
        return None

def demo_custom_configuration():
    """Demo custom configuration usage."""
    
    print("\n" + "="*70)
    print("DEMO: Custom Configuration")
    print("="*70)
    
    # Create analyzer with custom settings
    analyzer = StructuralTextAnalyzer.from_custom_config(
        output_dir='demo_custom_output',
        large_number_threshold=1e6,  # Lower threshold for large numbers
        min_sequence_length=2,       # Accept shorter sequences
        generate_plots=True,         # Enable visualizations
        output_format='markdown'     # Use markdown format
    )
    
    # Sample text for demonstration
    sample_text = """
    Iteration 1: residual norm = 1.23456E+05, convergence rate = 0.95
    Iteration 2: residual norm = 1.17283E+05, convergence rate = 0.94
    Iteration 3: residual norm = 1.10127E+05, convergence rate = 0.93
    Iteration 4: residual norm = 1.02418E+05, convergence rate = 0.92
    Iteration 5: residual norm = 9.42164E+04, convergence rate = 0.91
    
    The algorithm shows good convergence behavior with steady reduction
    in residual norms. No NaN or infinity values detected. 
    Processing completed successfully with 5 iterations.
    
    Memory usage: 2.34 GB
    Processing time: 12.45 seconds
    """
    
    try:
        # Analyze the sample text
        results = analyzer.analyze_text(sample_text, "custom_demo")
        
        # Generate outputs
        report_path = analyzer.generate_report()
        viz_files = analyzer.create_visualizations()
        
        # Print summary
        analyzer.print_summary()
        
        print("\nCUSTOM DEMO COMPLETED!")
        print(f"Report: {report_path}")
        print(f"Visualizations: {len(viz_files)} files created")
        
        return results
        
    except Exception as e:
        print(f"Custom demo failed: {e}")
        return None

def demo_modular_usage():
    """Demo individual module usage."""
    
    print("\n" + "="*70)
    print("DEMO: Modular Usage")
    print("="*70)
    
    from structural_analyzer.modules import TextStructureAnalyzer, NumericalAnalyzer, TrendAnalyzer
    from structural_analyzer.config import AnalysisConfig
    
    # Create configuration
    config = AnalysisConfig()
    
    # Sample text
    text = """This is a sample text for modular analysis. 
    It contains numbers like 123.456, 7.89E+03, and some NaN values.
    The text has multiple sentences of varying lengths.
    Short sentence. This is a much longer sentence with more words to analyze.
    Numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    """
    
    # Individual module demonstrations
    print("\n1. Text Structure Analysis:")
    text_analyzer = TextStructureAnalyzer(config)
    text_results = text_analyzer.analyze(text)
    print(f"   - Words: {text_results['basic_statistics']['total_words']}")
    print(f"   - Sentences: {text_results['basic_statistics']['total_sentences']}")
    print(f"   - Vocabulary: {text_results['basic_statistics']['vocabulary_size']}")
    
    print("\n2. Numerical Analysis:")
    num_analyzer = NumericalAnalyzer(config)
    num_results = num_analyzer.analyze(text)
    print(f"   - Numbers found: {num_results['summary']['total_numbers_found']}")
    print(f"   - Health score: {num_results['health_score']:.3f}")
    
    print("\n3. Trend Analysis:")
    sequences = num_analyzer.extract_sequences(text)
    if sequences:
        trend_analyzer = TrendAnalyzer(config)
        trend_results = trend_analyzer.analyze_multiple_sequences(sequences)
        print(f"   - Sequences found: {len(sequences)}")
        for seq_name, seq_data in sequences.items():
            print(f"   - {seq_name}: {len(seq_data)} points")
    else:
        print("   - No sequences found for trend analysis")
        
    print("\nMODULAR DEMO COMPLETED!")

def main():
    """Run all demos."""
    
    print("Structural Text Analyzer - Demo Suite")
    print("MiniMax Agent")
    print()
    
    # Ensure output directories exist
    os.makedirs('demo_output', exist_ok=True)
    os.makedirs('demo_custom_output', exist_ok=True)
    
    # Run demos
    try:
        # Demo 1: Computational log analysis
        demo_computational_log_analysis()
        
        # Demo 2: Custom configuration
        demo_custom_configuration()
        
        # Demo 3: Modular usage
        demo_modular_usage()
        
        print("\n" + "="*70)
        print("ALL DEMOS COMPLETED SUCCESSFULLY!")
        print("="*70)
        print("\nCheck the following directories for outputs:")
        print("- demo_output/")
        print("- demo_custom_output/")
        
    except KeyboardInterrupt:
        print("\nDemo interrupted by user.")
    except Exception as e:
        print(f"\nDemo suite failed: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    main()
